package com.example.mvvm_base.net;

import android.util.Log;

import com.blankj.utilcode.util.SPUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManger {
    //创建实例
    private static volatile RetrofitManger retrofitManger;
    private Retrofit retrofit;
    //获取实例的公共方法
    public  static RetrofitManger getInstance(){
        if(retrofitManger==null){
            synchronized (RetrofitManger.class){
                if(retrofitManger==null){
                    retrofitManger=new RetrofitManger();
                }
            }
        }
        return retrofitManger;
    }
    //获取retrofit的公共方法
    public Retrofit getRetrofit(){
        if(retrofit==null){
            retrofit=create();
        }
        return retrofit;
    }
    //实例化retrofit
    private Retrofit create(){
        OkHttpClient.Builder okhttp=new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .connectTimeout(30,TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        String token = SPUtils.getInstance().getString(Const.SP_TOKEN);
                        Log.d("aaa", "intercept: "+token);
                        Request.Builder builder = chain.request().newBuilder();
                        builder.addHeader(Const.PARAM_TOKEN,token);
                        return chain.proceed(builder.build());
                    }
                });
          Retrofit.Builder retrofitBuild=new Retrofit.Builder()
                  .baseUrl(Const.BASE_URL)
                  .client(okhttp.build())
                  .addConverterFactory(GsonConverterFactory.create())
                  .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        return retrofitBuild.build();
    }
}
